
#include "observable.h"

using namespace WtfEngine;

IObservable::IObservable()
: muNumObservers(0) {
};

IObservable::~IObservable() {
	NotifyObservers();
	if(!mrEvent.isNull())
		Kernel::GetInstance().ClearEvents(mrEvent);
};

void IObservable::AddObserver(const IFunctor<>::tRef &rObserver) {
	if(mrEvent.isNull()) {
		mrEvent = new ObservableNotifyEvent(this);
	};
	Kernel::GetInstance().BindEvent(mrEvent, rObserver);
	muNumObservers++;
};

void IObservable::RemoveObserver(const IFunctor<>::tRef &rObserver) {
	assert(muNumObservers > 0);
	Kernel::GetInstance().RemoveHandler(rObserver);
	muNumObservers--; // XXX DANGER: double removal
};

void IObservable::NotifyObservers() {
	if(muNumObservers > 0) {
		if(mrEvent.isNull()) {
			mrEvent = new ObservableNotifyEvent(this);
		};
		Kernel::GetInstance().ProcessEvent(mrEvent);
	};
};
